#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>

int main()
{

    int p[2] = {0};
    int val = pipe(p);
    if (val)
    {
        std::cout << "cerror pipe" << std::endl;
        return -1;
    }

    pid_t id = fork();
    if (id < 0)
    {
        std::cout << "fork error" << std::endl;
        return -1;
    }
    else if (id == 0)
    {
        // 子进程
        close(p[0]);
        int cnt = 0;

        while (true)
        {
            std::string messge = "I am child,my pid is : ";
            messge += std::to_string(getpid());
            messge += ",";
            messge += std::to_string(cnt);
            ssize_t st = ::write(p[1], messge.c_str(), sizeof(messge));
            cnt++;
            // sleep(5);
        }
    }
    else
    {
        // 父进程
        close(p[1]);

        char buffer[1024];
        while (true)
        {
            ssize_t n = ::read(p[0], buffer, 1024);
            buffer[n] = 0;
            std::cout << "child to father,messge: " << buffer << std::endl;
            sleep(5);
        }
        pid_t pid = waitpid(id, nullptr, 0);
    }

    return 0;
}